package org.scohen.juploadr.uploadapi.zooomr;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.scohen.juploadr.Messages;
import org.scohen.juploadr.app.PhotoSet;
import org.scohen.juploadr.ui.MessageUtils;
import org.scohen.juploadr.ui.Task;
import org.scohen.juploadr.uploadapi.zooomr.photosets.CreatePhotoSet;


public class CreateAllPhotosetsTask extends Task {
    private Collection<PhotoSet> sets;
    private ZooomrRestApi api;
    private String photoSetName;
    private int current;

    public CreateAllPhotosetsTask(Collection<PhotoSet> photoSets, ZooomrRestApi api) {
        this.sets = getNewPhotoSets(photoSets);
        this.api = api;
        this.max = sets.size() - 1;
        this.min = 0;
    }

    public String getTitle() {
        return Messages.getString("juploadr.ui.task.createphotsets.creating") + max + Messages.getString("juploadr.ui.task.createphotsets.photosets"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    public boolean hasSetsToCreate() {
        return sets.size() > 0;
    }

    private Collection<PhotoSet> getNewPhotoSets(Collection<PhotoSet> photoSets) {
        List<PhotoSet> rv = new LinkedList<PhotoSet>();
        Iterator iter = photoSets.iterator();
        while (iter.hasNext()) {
            PhotoSet set = (PhotoSet) iter.next();
            if (set.isNew()) {
                rv.add(set);
            }
        }
        return rv;
    }

    public void execute() {
        Iterator iter = sets.iterator();

        while (iter.hasNext()) {

            PhotoSet set = (PhotoSet) iter.next();
            photoSetName = set.getTitle();
            updateMessage();
            CreatePhotoSet create = new CreatePhotoSet(set);
            if (api.executeMethod(create)) {
                set.setNew(false);
            } else {
                // if we can't create, we will not be able to continue.
                if (create.getErrorCode() == 3) {
                    MessageUtils.showErrorMessage(create.getResponseHandler()
                            .getFailureReason());
                    break;
                }
            }
            updateProgress(current++);
        }
    }

    public String getMessage() {
        return Messages.getString("juploadr.ui.task.createphotsets.creating") + photoSetName + " (" + current + "/" + sets.size() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    }

}
